package com.zero.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.regexp.internal.RE;
import com.zero.entity.Family;
import com.zero.entity.FamilyMember;
import com.zero.mapper.FamilyMapper;
import com.zero.mapper.FamilyMemberMapper;
import com.zero.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Service
public class FamilyService {

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private FamilyMapper familyMapper;

    /**
     * 获取所有家庭的信息
     * @param family
     * @return
     */
    public Result getAllFamily(Family family){

        if (family != null && family.getPage() != null){
            if (family.getLimit() != null)
                PageHelper.startPage(family.getPage(), family.getLimit());
            else
                PageHelper.startPage(family.getPage(), 10);
        }else{
            PageHelper.startPage(1, 10);
        }

        List<Family> result = familyMapper.select(family);
        PageInfo pageInfo = new PageInfo(result);
        return Result.ok(result, pageInfo.getTotal());
    }

    /**
     * 获取当前用户的家庭通讯录
     * @param request
     * @return
     */
    public Result getAddressBook(HttpServletRequest request) {

        //获取请求者的id
        FamilyMember info = (FamilyMember) request.getAttribute("familyMember");
        if (info == null || info.getId() == null)
            return Result.fail("获取通讯录失败");

        //查询请求者的所有信息（主要要获取家庭id）
        FamilyMember familyMember = familyMemberMapper.selectById(info.getId());

        //查询该家庭的所有家庭成员的信息
        FamilyMember param = new FamilyMember();
        param.setFamilyId(familyMember.getFamilyId());
        List<FamilyMember> familyMembers = familyMemberMapper.select(param);

        return Result.ok("获取通讯录成功",familyMembers);
    }

    /**
     * 获取用户的家庭信息
     * @param request
     * @return
     */
    public Result getFamilyInfo(HttpServletRequest request){
        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到用户信息");
        familyMember = familyMemberMapper.selectById(familyMember.getId());

        Family family = familyMapper.selectById(familyMember.getFamilyId());
        if (family == null)
            return Result.fail("获取不到家庭信息");
        return Result.ok("获取家庭信息成功", family);
    }

    public Result updateFamilyInfo(Family family){
        if (family == null)
            return Result.fail("获取不到修改的信息");
        int row = familyMapper.update(family);
        if (row == 1)
            return Result.ok("修改家庭信息成功");
        return Result.fail("修改家庭信息失败");
    }

}
